<!--
 * @Author: early-autumn
 * @Date: 2020-05-11 18:44:32
 * @LastEditors: early-autumn
 * @LastEditTime: 2020-06-17 15:39:53
 -->
<template>
  <el-dialog
    title="修改患者信息"
    :visible="value"
    width="1080px"
    append-to-body
    @close="handleClose"
  >
    <el-form ref="form" label-width="100px" :model="form" :rules="rules">
      <el-row>
        <el-col :span="8">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="form.name" placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item label="生日" prop="birthday">
            <el-date-picker
              v-model="form.birthday"
              type="date"
              :style="{ width: '100%' }"
              :editable="false"
              :clearable="false"
              placeholder="选择生日"
              @input="handleBirthdayToAge"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="年龄" prop="age">
            <el-input
              v-model="form.age"
              placeholder="请输入姓名"
              @input="handleAgeToBirthday"
            />
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="form.sex">
              <el-radio
                v-for="option in sexOptions"
                :key="option.value"
                :label="option.value"
                >{{ option.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="地址" prop="province">
            <el-cascader
              v-model="location"
              :style="{ width: '100%' }"
              placeholder="请选择地址"
              :options="locationOptions"
              @change="handleLocationChange"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="详细地址" prop="addressDetailed">
            <el-input
              v-model="form.addressDetailed"
              placeholder="请输入详细地址"
            />
          </el-form-item>
          <el-form-item label="黄页编号" prop="yellowCode">
            <el-input v-model="form.yellowCode" placeholder="请输入黄页编号" />
          </el-form-item>
          <el-form-item label="正畸编号" prop="orthodonticsCode">
            <el-input
              v-model="form.orthodonticsCode"
              placeholder="请输入正畸编号"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="客户状态" prop="personStatus">
            <el-input
              v-model="form.personStatus"
              disabled
              placeholder="请输入客户状态"
            />
          </el-form-item>
          <el-form-item label="职业">
            <el-select
              v-model="form.profession"
              :style="{ width: '100%' }"
              placeholder="请选择职业"
            >
              <el-option
                v-for="option in professionalOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="推荐人" prop="referrer">
            <el-form
              v-if="!form.referrerId"
              ref="searchReferenceForm"
              :model="searchReference.form"
              :rules="searchReference.rules"
              inline
            >
              <el-form-item prop="keyword" :style="{ width: '100%' }">
                <el-input
                  v-model="searchReference.form.keyword"
                  placeholder="推荐人手机号"
                >
                  <el-button
                    slot="append"
                    icon="el-icon-search"
                    @click="handleSearchReferenceSubmit"
                  >
                    搜索
                  </el-button>
                </el-input>
              </el-form-item>
            </el-form>
            <el-tag
              v-else
              effect="dark"
              closable
              @close="handleSearchReferenceClose"
            >
              {{ form.referrerName }} {{ form.referrerPhoneNumber }}
            </el-tag>
          </el-form-item>
          <el-form-item
            v-if="form.referrerId"
            label="推荐人关系"
            prop="referrerRelation"
          >
            <el-select
              v-model="form.referrerRelation"
              :style="{ width: '100%' }"
              placeholder="请选择推荐人关系"
            >
              <el-option
                v-for="option in referrerRelationshipOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-tabs>
        <el-tab-pane>
          <el-row>
            <el-col :span="8">
              <el-form-item label="经济能力" prop="economics">
                <el-select
                  v-model="form.economics"
                  :style="{ width: '100%' }"
                  placeholder="请选择经济能力"
                >
                  <el-option
                    v-for="option in economicAbilityOptions"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="消费习惯" prop="consumptionCustom">
                <el-select
                  v-model="form.consumptionCustom"
                  :style="{ width: '100%' }"
                  placeholder="请选择消费习惯"
                >
                  <el-option
                    v-for="option in spendingHabitsOptions"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="身份证" prop="idCard">
                <el-input v-model="form.idCard" placeholder="请输入身份证" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="qq号" prop="qqNumber">
                <el-input v-model="form.qqNumber" placeholder="请输入qq号" />
              </el-form-item>
              <el-form-item label="微信号" prop="wechatNumber">
                <el-input
                  v-model="form.wechatNumber"
                  placeholder="请输入微信号"
                ></el-input>
              </el-form-item>
              <el-form-item label="Email" prop="email">
                <el-input v-model="form.email" placeholder="请输入Email" />
              </el-form-item>
              <el-form-item label="邮编" prop="postcode">
                <el-input v-model="form.postcode" placeholder="请输入邮编" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="婚姻状况" prop="maritalStatus">
                <el-radio-group v-model="form.maritalStatus">
                  <el-radio
                    v-for="option in maritalStatusOptions"
                    :key="option.value"
                    :label="option.value"
                  >
                    {{ option.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="有无小孩" prop="haveChild">
                <el-radio-group v-model="form.haveChild">
                  <el-radio
                    v-for="option in haveChildOptions"
                    :key="option.value"
                    :label="option.value"
                  >
                    {{ option.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="性格" prop="personality">
                <el-select
                  v-model="form.personality"
                  :style="{ width: '100%' }"
                  placeholder="请选择性格"
                >
                  <el-option
                    v-for="option in characterOptions"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
      <el-form-item label="备注">
        <el-input
          v-model="form.remarks"
          type="textarea"
          placeholder="请输入备注"
        ></el-input>
      </el-form-item>
    </el-form>
    <search-reference
      v-model="searchReference.visible"
      :keyword="searchReference.form.keyword"
      @ok="handleSearchReferenceOk"
    ></search-reference>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import dayjs from 'dayjs'
import { CodeToText, regionData, TextToCode } from 'element-china-area-data'
import { updatePerson } from '@/api/services/person'
import {
  characterOptions,
  customerStatusOptions,
  economicAbilityOptions,
  entityOptions,
  haveChildOptions,
  maritalStatusOptions,
  phoneOwnershipOptions,
  professionalOptions,
  referrerRelationshipOptions,
  sexOptions,
  spendingHabitsOptions,
  temporaryPatientOptions,
} from '@/utils/options'
import { sexEnum } from '@/utils/enums'
import { phoneNumberRegexp } from '@/utils/regexps'
import SearchReference from '../SearchReference'
import { mapState } from 'vuex'

export default {
  name: 'UpdatePatientPanel',
  components: {
    SearchReference,
  },
  model: {
    prop: 'value',
    event: 'close',
  },
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    patient: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      // 表单数据
      form: {},
      // 表单校验
      rules: {
        name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
        sex: [{ required: true, message: '性别不能为空', trigger: 'blur' }],
        age: [{ required: true, message: '年龄不能为空', trigger: 'blur' }],
        birthday: [
          { required: true, message: '生日不能为空', trigger: 'blur' },
        ],
        province: [
          { required: true, message: '地址不能为空', trigger: 'blur' },
        ],
        personStatus: [
          { required: true, message: '客户状态不能为空', trigger: 'blur' },
        ],
        yellowCode: [
          { required: true, message: '黄页编号不能为空', trigger: 'blur' },
        ],
        filingPerson: [
          { required: true, message: '建档人不能为空', trigger: 'blur' },
        ],
      },

      // 地址
      location: [],

      searchReference: {
        visible: false,
        form: {
          keyword: undefined,
        },
        rules: {
          keyword: [
            { required: true, message: '手机号不能为空', trigger: 'blur' },
            {
              pattern: phoneNumberRegexp,
              message: '手机号格式不正确',
              trigger: 'blur',
            },
          ],
        },
      },
    }
  },
  computed: {
    locationOptions() {
      return regionData
    },
    sexOptions() {
      return sexOptions
    },
    sexEnum() {
      return sexEnum
    },
    phoneOwnershipOptions() {
      return phoneOwnershipOptions
    },
    maritalStatusOptions() {
      return maritalStatusOptions
    },
    haveChildOptions() {
      return haveChildOptions
    },
    customerStatusOptions() {
      return customerStatusOptions
    },
    temporaryPatientOptions() {
      return temporaryPatientOptions
    },
    economicAbilityOptions() {
      return economicAbilityOptions
    },
    spendingHabitsOptions() {
      return spendingHabitsOptions
    },
    characterOptions() {
      return characterOptions
    },
    professionalOptions() {
      return professionalOptions
    },
    referrerRelationshipOptions() {
      return referrerRelationshipOptions
    },
    entityOptions() {
      return entityOptions
    },
    ...mapState({
      clinicName: (state) => state.clinic.clinicName,
    }),
  },
  watch: {
    value(newVal) {
      if (newVal) {
        this.init()
      } else {
        this.$refs.form.resetFields()
      }
    },
  },
  methods: {
    /**
     * 初始化表单数据
     */
    init() {
      this.form = {
        ...this.patient,
      }
      const { province, city, district, age } = this.patient
      this.location = [
        TextToCode[province].code,
        TextToCode[province][city].code,
        TextToCode[province][city][district].code,
      ]
      this.handleAgeToBirthday(age)
    },

    /**
     * 选择地址
     */
    handleLocationChange(e) {
      const [province, city, district] = e

      this.form.province = CodeToText[province]
      this.form.city = CodeToText[city]
      this.form.district = CodeToText[district]
    },
    /**
     * 提交
     */
    submit() {
      this.$refs.form.validate(async (valid) => {
        try {
          if (!valid) {
            return
          }

          this.loading = true

          const { age, birthday } = this.form
          const formData = {
            ...this.form,
            age: +age,
            birthday: dayjs(birthday).format('YYYY-MM-DD'),
            phoneNumber: undefined,
            phoneOwnership: undefined,
            arriveClinic: this.clinicName,
          }
          await updatePerson(formData)
          this.handleClose()
          this.msgSuccess('修改成功')
          this.$emit('ok', formData)
        } finally {
          this.loading = false
        }
      })
    },
    /**
     * 取消
     */
    handleClose() {
      this.$emit('close', false)
    },

    handleAgeToBirthday(age) {
      const year = dayjs().subtract(age, 'year').format('YYYY')
      const md = dayjs(this.birthday).format('MM-DD')

      this.form.birthday = dayjs(`${year}-${md}`)
    },

    handleBirthdayToAge(birthday) {
      this.form.age = dayjs().diff(dayjs(birthday), 'year')
    },

    handleSearchReferenceSubmit() {
      this.$refs.searchReferenceForm.validate((valid) => {
        if (!valid) {
          return
        }
        this.searchReference.visible = true
      })
    },

    handleSearchReferenceOk(e) {
      const { id, name, phoneNumber } = e
      this.form.referrerId = id
      this.form.referrerName = name
      this.form.referrerPhoneNumber = phoneNumber
    },

    handleSearchReferenceClose() {
      this.form.referrerId = undefined
      this.form.referrerName = undefined
      this.form.referrerPhoneNumber = undefined
      this.form.referrerRelation = undefined
    },
  },
}
</script>
